package com.hxci.controller;

import com.github.pagehelper.PageInfo;
import com.hxci.pojo.student;
import com.hxci.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hxci.service.AiAssistantService;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Controller
@RequestMapping("/student")
public class StudetController {

    @Autowired
    private AiAssistantService aiAssistantService;
    @Autowired
    private StudentService studentService;

    @GetMapping("/index")
    public String getStudentData(
            @RequestParam(required = false) String bname,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            Model model) {

        Map<String, Object> params = new HashMap<>();
        params.put("bname", bname);
        params.put("title", title);
        params.put("name", name);

        PageInfo<student> pageInfo = studentService.getStudentData(params, pageNum, pageSize);
        if (pageInfo.getPages() > 0 && pageNum > pageInfo.getPages()) {
            pageInfo = studentService.getStudentData(params, pageInfo.getPages(), pageSize);
        }
        List<String> classNames = studentService.getAllClassNames();
        List<String> titles = studentService.getAllTitles();
        int totalStudents = studentService.getTotalStudentCount(params);
        int totalStudentCount = studentService.getTotalStudentCount(); // 获取总人数

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("students", pageInfo.getList());
        model.addAttribute("classNames", classNames);
        model.addAttribute("titles", titles);
        model.addAttribute("selectedBname", bname);
        model.addAttribute("selectedTitle", title);
        model.addAttribute("selectedName", name);
        model.addAttribute("totalStudents", totalStudents);
        model.addAttribute("totalStudentCount", totalStudentCount); // 添加总人数到模型

        return "index";
    }

    @PostMapping("/updateScore")
    public String updateScore(
            @RequestParam String name,
            @RequestParam String title,
            @RequestParam String score,
            @RequestParam(required = false) Integer wid,
            @RequestParam(required = false) String bname,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            Model model) {

        if (title != null) {
            String t = title.trim();
            if (t.startsWith("第") && t.endsWith("次作业")) {
                String digits = t.replaceAll("[^0-9]", "");
                int n;
                if (!digits.isEmpty()) {
                    try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                } else {
                    String c = t.replace("第", "").replace("次作业", "").replace("作业", "");
                    n = toNumber(c);
                }
                if (n > 0) {
                    String realTitle = studentService.getTitleByIndex(n);
                    if (realTitle != null && !realTitle.isEmpty()) {
                        title = realTitle;
                    }
                }
            } else if (t.startsWith("作业")) {
                String c = t.replace("作业", "").trim();
                int n = toNumber(c);
                if (n > 0) {
                    String realTitle = studentService.getTitleByIndex(n);
                    if (realTitle != null && !realTitle.isEmpty()) {
                        title = realTitle;
                    }
                }
            }
        }

        studentService.updateScoreByNameAndTitle(name, title, score, wid);

        Map<String, Object> params = new HashMap<>();
        params.put("bname", bname);
        params.put("title", title);
        params.put("name", name);

        PageInfo<student> pageInfo = studentService.getStudentData(params, pageNum, pageSize);
        if (pageInfo.getPages() > 0 && pageNum > pageInfo.getPages()) {
            pageInfo = studentService.getStudentData(params, pageInfo.getPages(), pageSize);
        }
        List<String> classNames = studentService.getAllClassNames();
        List<String> titles = studentService.getAllTitles();
        int totalStudents = studentService.getTotalStudentCount(params);
        int totalStudentCount = studentService.getTotalStudentCount();

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("students", pageInfo.getList());
        model.addAttribute("classNames", classNames);
        model.addAttribute("titles", titles);
        model.addAttribute("selectedBname", bname);
        model.addAttribute("selectedTitle", title);
        model.addAttribute("selectedName", name);
        model.addAttribute("totalStudents", totalStudents);
        model.addAttribute("totalStudentCount", totalStudentCount);

        return "index";
    }

    private int toNumber(String c) {
        if (c == null || c.isEmpty()) return 0;
        c = c.replace("（", "").replace("）", "").replace("(", "").replace(")", "").trim();
        String digits = c.replaceAll("[^0-9]", "");
        if (!digits.isEmpty()) {
            try { return Integer.parseInt(digits); } catch (Exception e) { return 0; }
        }
        int val = 0;
        int tenIdx = c.indexOf("十");
        if (tenIdx >= 0) {
            int left = tenIdx == 0 ? 1 : mapChinese(c.substring(0, tenIdx));
            int right = tenIdx == c.length() - 1 ? 0 : mapChinese(c.substring(tenIdx + 1));
            if (left <= 0) left = 1;
            val = left * 10 + right;
        } else {
            val = mapChinese(c);
        }
        return val;
    }

    private int mapChinese(String s) {
        if (s == null || s.isEmpty()) return 0;
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            int v = 0;
            switch (ch) {
                case '一': v = 1; break;
                case '二': v = 2; break;
                case '三': v = 3; break;
                case '四': v = 4; break;
                case '五': v = 5; break;
                case '六': v = 6; break;
                case '七': v = 7; break;
                case '八': v = 8; break;
                case '九': v = 9; break;
                case '零': v = 0; break;
                default: v = 0; break;
            }
            total = total * 10 + v;
        }
        return total;
    }

}
